package com.ruoyi.project.socket.packet;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class L2Payload {

    private List<KV> list;
    private int len;

    public int getLen(){
        return len;
    }

    public L2Payload(){
        list = new ArrayList<>();
    }

    public void put(byte key,byte[] value){
        if(null==value||value.length==0)
            return;
        len+=1;
        len+=2;
        len+=value.length;
        list.add(new KV(key,value));
    }

    public byte[] l2Payload2Bytes(){
        ByteBuf buf = Unpooled.buffer(0,502);
        for(KV kv:list){
            try {
                buf.writeByte(kv.getKey());
                buf.writeShort(kv.getValue().length);
                buf.writeBytes(kv.getValue());
            }catch (IndexOutOfBoundsException e){
                log.info("l2payload超过了最大长度502");
                return null;
            }
        }
        byte[] bytes = new byte[buf.readableBytes()];
        buf.writeBytes(bytes);
        return bytes;
    }


    class KV{
        private byte key;

        private byte[] value;

        public KV(){}

        public KV(byte key, byte[] value) {
            this.key = key;
            this.value = value;
        }

        public byte getKey() {
            return key;
        }

        public void setKey(byte key) {
            this.key = key;
        }

        public byte[] getValue() {
            return value;
        }

        public void setValue(byte[] value) {
            this.value = value;
        }
    }
}
